package com.kaibes.admin.message;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kaibes.module.message.Message;
import com.kaibes.module.message.MessageService;
import com.kaibes.orm.core.core.Page;
import com.kaibes.web.thymeleaf.ThymeleafConfig;
import com.kaibes.web.util.WebUtils;

@Component
public class MessageUtils implements InitializingBean {

    @Autowired
    private ThymeleafConfig thymeleafConfig;
    @Autowired
    private MessageService messageService;
    
    public long countUnRead() {
        HttpServletRequest request = WebUtils.getRequest();
        return messageService.countByUserIdAndRead((Integer)request.getAttribute("userId"), false);
    }
    
    public long countReaded() {
        HttpServletRequest request = WebUtils.getRequest();
        return messageService.countByUserIdAndRead((Integer)request.getAttribute("userId"), true);
    }
    
    public Page<Message> page() {
        HttpServletRequest request = WebUtils.getRequest();
        int pageIndex = (int) request.getAttribute("page");
        boolean isReaded = (boolean) request.getAttribute("readed");
        int pageSize = 10; 
        Page<Message> page = messageService.pageByUserIdAndRead(pageIndex, pageSize, (Integer)request.getAttribute("userId"), isReaded);
        if (!isReaded) {
            List<Message> datas = page.getData();
            List<BigInteger> ids = new ArrayList<>();
            for (Message message : datas) {
                ids.add(message.getId());
            }
            messageService.updateReadByIds((Integer)request.getAttribute("userId"), ids);
        }
        return page;
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		thymeleafConfig.putStaticVariable("messageUtils", this);
	}
    
}
